<template>
	<el-dialog v-model="dialogVisible" title="新建用户" width="600" :before-close="hideModal">
		<div>
			<el-form ref="formRef" :model="form" label-width="auto">
				<el-form-item label="账号：" prop="name">
					<el-input v-model="form.account" placeholder="请输入" />
				</el-form-item>

				<el-form-item label="所属公司" prop="name">
					<el-input v-model="form.corp" placeholder="请输入" />
				</el-form-item>

				<el-form-item label="过期时间" prop="name">
					<el-date-picker v-model="form.expireTime" type="dates" placeholder="请选择" />
				</el-form-item>

				<el-form-item label="密码" prop="name">
					<el-input v-model="form.password" placeholder="请输入" />
				</el-form-item>

				<el-form-item label="" prop="name">
					<el-button @click="form.password = generatePassword()">随机生成密码</el-button>
				</el-form-item>
			</el-form>
		</div>
		<template #footer>
			<div class="dialog-footer">
				<el-button @click="hideModal">取消</el-button>
				<el-button type="primary" @click="submit"> 确定 </el-button>
			</div>
		</template>
	</el-dialog>
</template>

<script setup lang="ts" name="loginIndex">
import { onMounted, reactive, ref } from 'vue';
import { NextLoading } from '/@/utils/loading';
import { getUserList, addUserList } from '/@/api/api';
import { formatDate } from '/@/utils/util';

const emit = defineEmits(['handleClose']);

const tableData = reactive({});
const form = ref({});
const dialogVisible = ref(false);

async function submit() {
	let { code, data } = await addUserList({
		...form.value,
	});
	if (code == 200) {
		hideModal();
	}
}

function generatePassword() {
	const chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
	let password = '';

	// Ensure at least one digit and one English character
	let hasDigit = false;
	let hasLetter = false;

	while (password.length < 8) {
		const randomIndex = Math.floor(Math.random() * chars.length);
		const char = chars[randomIndex];

		if (/[0-9]/.test(char)) {
			hasDigit = true;
		} else if (/[a-zA-Z]/.test(char)) {
			hasLetter = true;
		}

		password += char;
	}

	if (!hasDigit || !hasLetter) {
		return generatePassword(); // Retry if requirements are not met
	}

	return password;
}

async function getData() {
	let { code, data } = await getUserList({
		page: 1,
		size: 10000,
	});
	if (code == 200) {
		tableData.data = data.list;
		console.log('tableData', tableData);
	}
}

function showModal(row) {
	console.log('🚀 ~ showModal ~ row:', row);
	dialogVisible.value = true;

	if (row) {
		form.value = row;
		form.value.expireTime = formatDate(form.value.expireTime);
	}
	getData();
}

function hideModal() {
	for (let obj in form.value) {
		form.value[obj] = null;
	}

	dialogVisible.value = false;
	emit('handleClose');
}

defineExpose({
	hideModal,
	showModal,
});
</script>

<style scoped lang="scss"></style>
